#pragma once

#include "../source/server.hpp"
#include <fstream>
#include <ostream>
#include <sys/stat.h>

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class Util
{
public:
    //字符串的分割
    static size_t Split(const std::string &src,const std::string &sep,std::vector<std::string> *arry)
    {
        size_t offset = 0;
        while(offset < src.size())
        {
            //记录分隔符
            size_t pos = src.find(sep,offset);
            /**
             * 当没有找到分隔符时(也就是走到了字符串末尾)
             * "abc,def,tyu"
             * "abc,def,tyu,"-->对应的判断if(pos == src.size()) break;
            */
            if(pos == std::string::npos)
            {
                //如果末尾是个sep,那么就不打印了
                if(pos == src.size()) break;
                //如果末尾不是sep,那就把末尾的子串添加到arry中
                arry->push_back(src.substr(offset));
                return arry->size();
            }
            /**
             * 当src中出现连续的sep,那么也不打印直接跳过
             * "abc,,,,def,tyu"-->if(pos == offset)
            */
            if(pos == offset)
            {
                offset = pos + sep.size();
                continue;
            }
            arry->push_back(src.substr(offset,pos - offset));
            offset = pos + sep.size();
        }
        return arry->size();
    }

    //读取文件内容
    // static bool ReadFile(const std::string &filename,Buffer *buf)
    // {
    //     std::ifstream ifs(filename,std::ios::binary);//二进制打开方式
    //     if(ifs.is_open() == false)
    //     {
    //         printf("open %s file failed!",filename.c_str());
    //         return false;
    //     }
    //     //获取文件长度
    //     ifs.seekg(0,ifs.end);
    //     size_t fsize = ifs.tellg();
    //     ifs.seekg(0,ifs.beg);
    //     //开辟文件大小的空间
    //     std::string str;
    //     str.resize(fsize);
    //     ifs.read(&str[0],fsize);
    //     if(ifs.good() == false)
    //     {
    //         printf("read %s file failed!",filename.c_str());
    //         ifs.close();
    //         return false;
    //     }
    //     //把文件放到buffer中 
    //     buf->WriteStringAndPush(str);
    //     return true;
    // }
    //读取文件内容
    static bool ReadFile(const std::string &filename,std::string *buf)
    {
        std::ifstream ifs(filename,std::ios::binary);//二进制打开方式
        if(ifs.is_open() == false)
        {
            printf("open %s file failed!",filename.c_str());
            return false;
        }
        //获取文件长度
        ifs.seekg(0,ifs.end);
        size_t fsize = ifs.tellg();
        ifs.seekg(0,ifs.beg);
        //开辟文件大小的空间
        buf->resize(fsize);
        ifs.read(&(*buf)[0],fsize);
        if(ifs.good() == false)
        {
            printf("read %s file failed!",filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    //向文件中写入
    static bool WriteFile(const std::string& filename,const std::string &buf)
    {
        std::ofstream ofs(filename,std::ios::binary | std::ios::trunc);
        if(ofs.is_open() == false)
        {
            printf("open %s file failed!",filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(),buf.size());
        if(ofs.good() == false)
        {
            printf("write %s file failed!",filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    /**
     * URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
     * 编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
     * 不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
     * RFC3986文档规定，编码格式 %HH 
     * W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
    */
    static std::string UrlEncode(const std::string url,bool convert_space_to_plus)
    {
        std::string res;
        for(auto &e :url)
        {
            if(e == '.' || e == '_' || e == '~' || isalnum(e))
            {
                res += e;
                continue;
            }
            if(e == ' ' && convert_space_to_plus == true)
            {
                res += '+';
                continue;
            }
            //剩下的字符按照%HH格式编译
            char tmp[4] = {0};
            //4表示限制最多4个长度
            snprintf(tmp,4,"%%%02X",e);
            res += tmp;
        }
        return res;
    }
    static char HEXTOI(char c)
    {
        if(c >= '0' && c <= '9')
            return c - '0';
        else if(c >= 'a' && c <= 'z')
            return c - 'a' + 10;
        else if(c >= 'A' && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }
    //URL解码
    //遇到了%，则把其后的两个字符,转换成数字,第一个字符左移4位(*16),再加上第二个字符
    static std::string UrlDecode(const std::string url,bool convert_plus_to_space)
    {
        std::string res;
        for(int i = 0; i < url.size(); i++)
        {
            if(url[i] == '+' && convert_plus_to_space == true)
            {
                res += '+';
                continue;
            }
            if(url[i] == '%' && (i + 2) < url.size())
            {
                char v1 = HEXTOI(url[i+1]);
                char v2 = HEXTOI(url[i+2]);
                char v = (v1 << 4) + v2;
                res +=v;
                i +=2;
                continue;
            }
            res += url[i];
        }
        return res;
    }
    //响应状态码的描述信息获取
    static std::string StatuDesc(int x)
    {
        auto it = _statu_msg.find(x);
        if(it == _statu_msg.end())
            return "Unknow";
        return it->second;
    }
    //获取文件后缀
    static std::string ExtMime(const std::string &filename)
    {
        size_t pos = filename.find_last_of('.');
        if(pos == std::string::npos)
            return "applocation/occet-stream";
        std::string exit = filename.substr(pos);
        auto it = _mime_msg.find(exit);
        if(it == _mime_msg.end())
            return "applocation/occet-stream";
        return it->second;
    }
    //文件和目录的测试在statu_mime.cc当中
    //判断文件是否是目录
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }
    //判断文件是否是普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }
    //http请求有效路径的判断
    static bool ValidPath(const std::string& path)
    {
        std::vector<std::string> subpath;
        Split(path,"/",&subpath);
        int level = 0;
        for(auto &e : subpath)
        {
            if(e == "..")
            {
                level--;
                if(level == 0) return false;
                continue;
            }
            level++;
        }
        return true;
    }
    //
};